using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using centrafuse.Plugins;
using Altbrot.Yawr.ShoutCast;
using Altbrot.Yawr.Entities;
using System.Collections.Generic;
using System.Reflection;
using Altbrot.Yawr.Buslogic;
using Altbrot.Yawr.Player;

namespace Altbrot.Yawr.Plugin
{
	/// <summary>
	/// A simple HelloWorld plugin for the CentraFuse SDK
    /// - nemo
	/// </summary>
    public class Yawr : CFPlugin, IYawr
    {

        #region Variables

        private const string PluginName = "Yawr";
        private const string PluginPath = @"plugins\" + PluginName + @"\";
        private const string PluginPathSkins = PluginPath + @"Skins\";
        private const string PluginPathLanguages = PluginPath + @"Languages\";
        private const string PluginPathIcons = PluginPath + @"Icons\";
        private const string ConfigurationFile = "config.xml";
        private const string LogFile = "yawr.log";
        private const string DbFile = "FeedItemDb.sdf";
        private bool IsHidden = true;
        private string MainTitle = string.Empty;

        // we write the log to the appropriate users local appdata directory in the Plugins subfolder...
        public static string LogFilePath = CFTools.AppDataPath + "\\Plugins\\" + PluginName + "\\" + LogFile;
        public static string DbFilePath = CFTools.StartupPath + "\\Plugins\\" + PluginName + "\\Database\\" + DbFile;      

        private const int ImageFolderIndex = 0;
        private const int ImageEmptyIndex = 1;

        private CFControls.CFListView MainListView;
        private CFControls.CFLabel MainLabel;
        private ScrollingText ScrollingText;
        
        private ShoutCastManager _shoutCastManager;
        private readonly string _tmpFilePath = "tunein-station.pls";
        private FeedItem _selectedFeedItem;
        private List<FeedItem> _feedItemList;
        private Dictionary<FeedItemCategory, int> indexHistory;
        private UpdateProgress _updateProgressDialog;

        public FeedItem SelectedFeedItem
        {
            get
            {
                return _selectedFeedItem;
            }
            set
            {
                _selectedFeedItem = value;
                _shoutCastManager.SelectedFeedItem = _selectedFeedItem;
            }
        }

        public List<FeedItem> FeedItemList
        {
            get
            {
                return _feedItemList;
            }
            set
            {
                _feedItemList = value;
                BindMainListView(_feedItemList);
            }
        }

        public void SetAudioStreamDataChangeEvent(YawrAudioStreamDataChangeEventHandler handler) 
        {
            base.CF_events.audioStreamDataChange += new CFAudioStreamDataChangeEventHandler(handler);
        }

        #endregion

        #region Construction

        /// <summary>
        /// Default constructor (creates the plugin and sets its properties).
        /// </summary>
        public Yawr()
        {
            // nothing special to do here
            // in a more advanced plugin, flags and such can be done here
            // Usually it is safe to just use the CF_initPlugin() override to do initialization   
            this.CF_params.pauseAudio = true;
        }

        #endregion

        #region CFPlugin methods

        /// <summary>
        /// Initializes the plugin.  This is called from the main application
        /// when the plugin is first loaded.
        /// </summary>
        public override void CF_pluginInit()
        {
            try
            {
                // Call writeModuleLog() with the string startup() to keep only last 2 runtimes...
                // Note CF_loadConfig() must be called before WriteLog() can be used
                WriteLog("startup");
                WriteLog("CF_pluginInit");

                // CF3_initPlugin() Will configure pluginConfig and pluginLang automatically
                // All plugins must call this method once
                this.CF3_initPlugin("Yawr", true);

                // All controls should be created or Setup in CF_localskinsetup.
                // This method is also called when the resolution or skin has changed.
                this.CF_localskinsetup();

                LoadSettings();

                // add event handlers for keyboard and power mode change
                this.CF_events.powerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(HelloWorld_CF_Event_powerModeChanged);
                this.KeyDown += new KeyEventHandler(HelloWorld_KeyDown);
                
                // init shoutcast stuff
                string filePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), _tmpFilePath);
                Uri baseUri = new Uri(this.pluginLang.ReadField("APPLANG/YAWR/RSSFEEDLINK"));

                // progress dialog
                this._updateProgressDialog = new UpdateProgress(PluginName, this.MainForm);
                this._updateProgressDialog.CF_pluginInit();

                _shoutCastManager = new ShoutCastManager(baseUri, filePath, new DatabaseBuslogicManager(DbFilePath), this);
                _shoutCastManager.GetBaseStepCompleted += new GetStepCompletedEventHandler(ShoutCastManager_GetStepCompleted);
                _shoutCastManager.GetNextStepCompleted += new GetStepCompletedEventHandler(ShoutCastManager_GetStepCompleted);
                _shoutCastManager.GetPrevStepCompleted += new GetStepCompletedEventHandler(ShoutCastManager_GetStepCompleted);
                _shoutCastManager.UpdateCompleted += new UpdateCompletedEventHandler(_shoutCastManager_UpdateCompleted);
                _shoutCastManager.OnPlayerStatusTextChanged += new Altbrot.Yawr.Player.PlayerStatusChangedEventHandler(_shoutCastManager_OnPlayerStatusTextChanged);
                _shoutCastManager.OnMediaChanged += new MethodInvoker(_shoutCastManager_OnMediaChanged);
                _shoutCastManager.UpdateProgressChanged += new UpdateProgressChangedEventHandler(_shoutCastManager_UpdateProgressChanged);

                indexHistory = new Dictionary<FeedItemCategory, int>();
                indexHistory.Add(FeedItemCategory.Genre, -1);
                indexHistory.Add(FeedItemCategory.Radio, -1);
                indexHistory.Add(FeedItemCategory.Station, -1);

                // init shoutcast base list
                _shoutCastManager.GetBaseStepAsync();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }                        

        /// <summary>
        /// This is called to setup the skin.  This will usually be called in CF_pluginInit.  It will 
        /// also called by the system when the resolution has been changed.
        /// </summary>
        public override void CF_localskinsetup()
        {
            WriteLog("CF_localskinsetup");

            // Read the skin file, controls will be automatically created
            // CF_localskinsetup() should always call CF3_initSection() first, with the exception of setting any
            // CF_displayHooks flags, which affect the behaviour of the CF3_initSection() call.
            this.CF3_initSection("Yawr");

            // init controls
            MainListView = listviewArray[0];
            MainListView.SelectedIndexChanged += new EventHandler(MainListView_SelectedIndexChanged);
            MainListView.DoubleClick += new EventHandler(MainListView_DoubleClick);
            MainListView.Padding = new Padding(10);

            MainLabel = labelArray[CF_getLabelID("LblMainDesc")];

            ScrollingText = new ScrollingText();
            ScrollingText.ScrollDirection = ScrollDirection.RightToLeft;
            ScrollingText.StopScrollOnMouseOver = false;
            ScrollingText.Bounds = new Rectangle(258, 62, 270, 42);
            ScrollingText.ScrollText = string.Empty;
            ScrollingText.BackColor = Color.Transparent;
            ScrollingText.BackgroundBrush = new SolidBrush(Color.FromArgb(0, 255, 255, 255));
            ScrollingText.Font = new Font("Century Gothic", 28, FontStyle.Bold);
            ScrollingText.ForeColor = Color.White;
            ScrollingText.BorderColor = Color.Transparent;
            ScrollingText.TextScrollSpeed = 20;
            ScrollingText.TextScrollDistance = 1;
            Controls.Add(ScrollingText);
        }       

        /// <summary>
        /// This is called by the system when it exits or the plugin has been deleted.
        /// </summary>
        public override void CF_pluginClose()
        {
            base.CF_pluginClose(); // calls form Dispose() method
        }

        /// <summary>
        /// Cs the f_plugin hide.
        /// </summary>
        public override void CF_pluginHide()
        {
            this.IsHidden = true;
            base.CF_pluginHide();            
        }

        /// <summary>
        /// This is called by the system when a button with this plugin action has been clicked.
        /// </summary>
        public override void CF_pluginShow()
        {
            this.IsHidden = false;                      
            try
            {
                if (!base.CF_getConnectionStatus())
                    base.CF_systemCommand(CF_Actions.CONNECT, base.CF_displayHooks.rearScreen ? "REARSCREEN" : "");

                base.CF_pluginShow();
            }            
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
            
        }

        /// <summary>
        /// This is called by the system when the plugin setup is clicked.
        /// </summary>
        /// <returns>Returns the dialog result.</returns>
        public override DialogResult CF_pluginShowSetup()
        {
            WriteLog("CF_pluginShowSetup");

            // Return DialogResult.OK for the main application to update from plugin changes.
            DialogResult returnvalue = DialogResult.Cancel;

            try
            {
                // Creates a new plugin setup instance. If you create a CFDialog or CFSetup you must
                // set its MainForm property to the main plugins MainForm property.
                Setup setup = new Setup(this.MainForm, this.pluginConfig, this.pluginLang);
                returnvalue = setup.ShowDialog();
                if (returnvalue == DialogResult.OK)
                {
                    LoadSettings();
                }
                setup.Close();
                setup = null;
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }

            return returnvalue;
        }

        /// <summary>
        /// This method is called by the system when it pauses all audio.
        /// </summary>
        public override void CF_pluginPause()
        {
            //this.CF_params.controlPlayControls = false;            
            this.BtnStopOnClick();
            WriteLog("CF_pluginPause");
        }

        /// <summary>
        /// This is called by the system when it resumes all audio.
        /// </summary>
        public override void CF_pluginResume()
        {
            WriteLog("CF_pluginResume");
        }

        /// <summary>
        /// Used for plugin to plugin communication. Parameters can be passed into CF_Main_systemCommands
        /// with CF_Actions.PLUGIN, plugin name, plugin command, and a command parameter.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="param1">The first parameter.</param>
        /// <param name="param2">The second parameter.</param>
        public override void CF_pluginCommand(string command, string param1, string param2)
        {
            WriteLog("CF_pluginCommand: " + command + " " + param1 + ", " + param2);
        }

        /// <summary>
        /// Used for retrieving information from plugins. You can run CF_getPluginData with a plugin name,
        ///	command, and parameter to retrieve information from other plugins running on the system.
        /// </summary>
        /// <param name="command">The command to execute.</param>
        /// <param name="param">The parameter.</param>
        /// <returns>Returns whatever is appropriate.</returns>
        public override string CF_pluginData(string command, string param)
        {
            WriteLog("CF_pluginData: " + command + " " + param);
            string returnValue = "";
            return returnValue;
        }

        /// <summary>
        /// Called on control clicks, down events, etc, if the control has a defined CML action parameter in the skin xml.
        /// </summary>
        /// <param name="id">The command to execute.</param>
        /// <param name="state">Button State.</param>
        /// <returns>Returns whatever is appropriate.</returns>
        public override bool CF_pluginCMLCommand(string command, string[] strparams, CF_ButtonState state, bool rear)
        {
            if (state != CF_ButtonState.Click)
                return false;

            WriteLog("CF_pluginCMLCommand: " + command);

            switch (command.ToUpper())
            {
                //case "CENTRAFUSE.MAIN.PLAY": BtnStopOnClick(); return true;                    
                case "BTNCLOSEONCLICK": BtnCloseOnClick(); return true;
                case "BTNPLAYONCLICK": BtnPlayOnClick(); return true;
                case "BTNSTOPONCLICK": BtnStopOnClick(); return true;
                case "BTNPGUPONCLICK": BtnPgUpOnClick(); return true;
                case "BTNPGDOWNONCLICK": BtnPgDownOnClick(); return true;
                case "BTNHOMEONCLICK": BtnHomeOnClick(); return true;
                case "BTNPREVONCLICK": BtnPrevOnClick(); return true;
                case "BTNNEXTONCLICK": BtnNextOnClick(); return true;
                case "BTNUPDATEONCLICK": BtnUpdateOnClick(); return true;
                case "BTNMOREONCLICK": BtnMoreOnClick(); return true;
                case "BTNSEARCHONCLICK": BtnSearchOnClick(); return true;
                case "BTNFAVONCLICK": BtnFavOnClick(); return true;
                case "BTNLESSONCLICK": BtnLessOnClick(); return true;
                case "CENTRAFUSE.MAIN.PLAYPAUSE":
                    if (this._shoutCastManager.PlayerState == StreamPlayerPlayState.wmppsPlaying)
                        BtnStopOnClick();
                    else if (this._shoutCastManager.PlayerState == StreamPlayerPlayState.wmppsStopped && !this.IsHidden)
                        BtnPlayOnClick();
                    return false;
            }

            return false;
        }

        public override string CF_pluginCMLData(CF_CMLTextItems textitem)
        {
            try
            {
                switch (textitem)
                {
                    case CF_CMLTextItems.MediaMode:
                        return "";
                    case CF_CMLTextItems.MediaPosition:
                        return "";
                    case CF_CMLTextItems.MediaStation:
                        return "";
                    case CF_CMLTextItems.MediaTitle:
                        return "";
                    case CF_CMLTextItems.MainTitle:
                        return this.MainTitle;
                    default:
                        return "";
                }
            }
            catch (Exception exception)
            {
                CFTools.writeError(exception.Message, exception.StackTrace);
            }
            return this.MainTitle;
        }

        #endregion

        #region System Functions

        private void LoadSettings()
        {
            // The display name is shown in the application to represent
            // the plugin.  This sets the display name from the configuration file.
            this.CF_params.displayName = this.pluginLang.ReadField("/APPLANG/YAWR/DISPLAYNAME");
            CFTools.writeLog("YAWR", "New display name = " + this.CF_params.displayName);
        }

        private void WriteLog(string msg)
        {
            try
            {
                if (Boolean.Parse(this.pluginConfig.ReadField("/APPCONFIG/LOGEVENTS")))
                    CFTools.writeModuleLog(msg, LogFilePath);
            }
            catch { }
        }

        private void BindMainListView(List<FeedItem> _feedItemList)
        {
            MainListView.ClearList();
            MainListView.ListImages = new ArrayList();
            MainListView.ListImages.Add(new Bitmap(PluginPathSkins + SkinReader.currentSkin + @"\favicon.png"));
            foreach (FeedItem item in _feedItemList)
            {
                if (item.IsFavorite != null && (bool)item.IsFavorite)
                {
                    MainListView.Items.Add(new CFControls.CFListViewItem(item.Title, item.Id.ToString(), 0, false));
                }
                else
                {
                    MainListView.Items.Add(new CFControls.CFListViewItem(item.Title, item.Id.ToString()));
                }
            }
            
            this.SelectedFeedItem = FeedItemList.Find(i => String.Compare(i.Id.ToString(), MainListView.SelectedItem.Value, true) == 0);
            CalcStateText(_shoutCastManager.GetCurrentState());
        }

        private void CalcStateText(FeedItemCategory feedItemCategory)
        {
            switch (feedItemCategory)
            {
                case FeedItemCategory.Genre:
                    this.MainLabel.Text = this.pluginLang.ReadField("/APPLANG/YAWR/MAINLABELGENRE");
                    break;
                case FeedItemCategory.Station:
                    this.MainLabel.Text = this.SelectedFeedItem.Genre;
                    break;
                case FeedItemCategory.Radio:                    
                    break;
                case FeedItemCategory.Undefined:                    
                    break;
                default:
                    break;
            }
            this.Invalidate(new Rectangle(MainLabel.Bounds.X, MainLabel.Bounds.Y, MainLabel.Bounds.Width, MainLabel.Bounds.Height), false);
        }

        private void GetIndexHistory()
        {
            if (this.SelectedFeedItem != null)
            {
                FeedItemCategory cat = (FeedItemCategory)Enum.Parse(typeof(FeedItemCategory), this.SelectedFeedItem.Category);
                MainListView.SelectedIndex = indexHistory[cat];
            }
        }

        private void SetIndexHistory()
        {
            if (this.SelectedFeedItem != null)
            {
                FeedItemCategory cat = (FeedItemCategory)Enum.Parse(typeof(FeedItemCategory), this.SelectedFeedItem.Category);
                indexHistory[cat] = MainListView.SelectedIndex;
            }
        }

        private void ShowProgessDialog()
        {
            try
            {                
                this._updateProgressDialog.ShowDialog();

            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        #endregion

        #region Soundcast Events

        void _shoutCastManager_OnMediaChanged()
        {
            string text = _shoutCastManager.MediaName + "   " + _shoutCastManager.MediaBitrate + "kbit";
            ScrollingText.ScrollText = text;
            //base.CF_updateText("MainTitle", text);
            this.MainTitle = text;
        }

        void _shoutCastManager_OnPlayerStatusTextChanged(string status)
        {
            if (!string.IsNullOrEmpty(status))
            {
                ScrollingText.ScrollText = status;
                //base.CF_updateText("MainTitle", status); 
                this.MainTitle = status;
            }            
        }

        void _shoutCastManager_UpdateProgressChanged(object sender, UpdateProgressEventArgs e)
        {
            if (this._updateProgressDialog.Visible)
            {
                this._updateProgressDialog.ProgressMessage = e.UpdateMessageValue;
                this._updateProgressDialog.ProgressLevel = @"Progress:   " + e.UpdateProgressValue.ToString() + "%";
            }
        }

        void _shoutCastManager_UpdateCompleted(object sender, UpdateCompletedEventArgs e)
        {
            this._updateProgressDialog.Close();
            if (e.Error != null)
            {
                CFTools.writeError(e.Error.Message);
            }
            else if (e.FeedList != null && e.FeedList.Count > 0)
            {
                FeedItemList = e.FeedList;
            }
        }       

        private void ShoutCastManager_GetStepCompleted(object sender, GetStepCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                CFTools.writeError(e.Error.Message);
            }
            else if (e.FeedList != null && e.FeedList.Count > 0)
            {
                FeedItemList = e.FeedList;
                GetIndexHistory();
            }
        }

        #endregion

        #region Control Events

        private void MainListView_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                //this._shoutCastManager.GetNextStepAsync();
                BtnAddToFavOnClick();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void MainListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.SelectedFeedItem = FeedItemList.Find(i => String.Compare(i.Id.ToString(), MainListView.SelectedItem.Value, true) == 0);
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnCloseOnClick()
        {
            try
            {
                base.CF_systemCommand(CF_Actions.MAINMENU);
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnPlayOnClick()
        {
            try
            {
                if (_shoutCastManager.GetCurrentState() == FeedItemCategory.Radio)
                {
                    _shoutCastManager.PlayUrl();
                }
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnStopOnClick()
        {
            try
            {
                _shoutCastManager.Stop();
                ScrollingText.ScrollText = string.Empty;
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnPgUpOnClick()
        {
            try
            {
                MainListView.pageUp();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnPgDownOnClick()
        {
            try
            {
                MainListView.pageDown();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnHomeOnClick()
        {
            try
            {
                _shoutCastManager.GetBaseStepAsync();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnPrevOnClick()
        {
            try
            {                
                _shoutCastManager.GetPrevStepAsync();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnNextOnClick()
        {
            try
            {
                SetIndexHistory();
                _shoutCastManager.GetNextStepAsync();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }        

        private void BtnFavOnClick()
        {
            try
            {
                FeedItemList = _shoutCastManager.GetFavoritesList();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnLessOnClick()
        {
            try
            {
                buttonArray[CF_getButtonID("BtnLess")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnLess")].Text = "";

                buttonArray[CF_getButtonID("BtnFav")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnFav")].Text = "";

                buttonArray[CF_getButtonID("BtnSearch")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnSearch")].Text = "";

                buttonArray[CF_getButtonID("BtnUpdate")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnUpdate")].Text = "";

                buttonArray[CF_getButtonID("BtnMore")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnMore")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNMORE");

                buttonArray[CF_getButtonID("BtnPrev")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnPrev")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNPREV");

                buttonArray[CF_getButtonID("BtnNext")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnNext")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNNEXT");

                buttonArray[CF_getButtonID("BtnHome")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnHome")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNHOME");

                this.Invalidate();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnAddToFavOnClick()
        {
            try
            {
                if (_shoutCastManager.GetCurrentState() == FeedItemCategory.Station)
                {
                    _shoutCastManager.ToggleFavorite();
                    int tmpIndex = this.MainListView.SelectedIndex;
                    this.FeedItemList = _shoutCastManager.GetStationList(this.SelectedFeedItem.Genre);
                    this.MainListView.SelectedIndex = tmpIndex; 
                }
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnSearchOnClick()
        {
            try
            {
                // Update the text to what user enters in osk
                object tempobject;
                string resultvalue, resulttext;
                if (this.CF_systemDisplayDialog(CF_Dialogs.OSK, this.pluginLang.ReadField("/APPLANG/YAWR/ENTERTEXT"), "", null, out resultvalue, out resulttext, out tempobject, null, true, true, true, true, false, false, 1) == DialogResult.OK)
                {
                    FeedItemList = _shoutCastManager.Search(resultvalue);
                }
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnMoreOnClick()
        {
            try
            {
                buttonArray[CF_getButtonID("BtnLess")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnLess")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNLESS");

                buttonArray[CF_getButtonID("BtnFav")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnFav")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNFAV");

                buttonArray[CF_getButtonID("BtnSearch")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnSearch")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNSEARCH");

                buttonArray[CF_getButtonID("BtnUpdate")].buttonEnabled = true;
                buttonArray[CF_getButtonID("BtnUpdate")].Text = this.pluginLang.ReadField("/APPLANG/YAWR/BTNUPDATE");

                buttonArray[CF_getButtonID("BtnMore")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnMore")].Text = "";
                
                buttonArray[CF_getButtonID("BtnPrev")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnPrev")].Text = "";

                buttonArray[CF_getButtonID("BtnNext")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnNext")].Text = "";

                buttonArray[CF_getButtonID("BtnHome")].buttonEnabled = false;
                buttonArray[CF_getButtonID("BtnHome")].Text = "";

                this.Invalidate();
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        private void BtnUpdateOnClick()
        {
            try
            {
                _shoutCastManager.UpdateAsync();
                ShowProgessDialog();                
                //CF_systemCommand(CF_Actions.SHOWINFO, LanguageReader.GetText("APPLANG/GENERIC/LOADING"));
            }
            catch (Exception errmsg) { CFTools.writeError(errmsg.ToString()); }
        }

        #endregion

        #region CF events

        private void HelloWorld_CF_Event_powerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
        {

        }


        // If the plugin uses back/forward buttons, we need to catch the left/right keyboard commands too...
        private void HelloWorld_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;

            if (e.KeyCode == Keys.Left)
            {
                //---------------------------------------------------------------------------
                // TODO: replace this if needed
                //--------------------------------------------------------------------------- 
                //this.back_Click(this, new MouseEventArgs(MouseButtons.Left,1,0,0,0));
            }
            else if (e.KeyCode == Keys.Right)
            {
                //---------------------------------------------------------------------------
                // TODO: replace this if needed
                //--------------------------------------------------------------------------- 
                //this.forward_Click(this, new MouseEventArgs(MouseButtons.Left,1,0,0,0));
            }
        }

        #endregion

    }
}
